/*
* Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

use crate::bincode::Decoder;

pub trait BorrowDecode<'de>: Sized {
    unsafe fn borrow_decode_unchecked<D: Decoder>(decoder: &mut D, buf: &'de [u8]) -> Self;
    fn borrow_decode<D: Decoder>(decoder: &mut D, buf: &'de [u8]) -> Result<Self, D::Error>;    
}

impl<'de> BorrowDecode<'de> for &'de [u8] {
    unsafe fn borrow_decode_unchecked<D: Decoder>(decoder: &mut D, buf: &'de [u8]) -> Self {
        let len = unsafe { decoder.get_u32_unchecked(buf) };
        unsafe { decoder.get_bytes_unchecked(buf, len as usize) }
    }

    fn borrow_decode<D: Decoder>(decoder: &mut D, buf: &'de [u8]) -> Result<Self, D::Error> {
        let len = decoder.get_u32(buf)?;
        Ok(decoder.get_bytes(buf, len as usize)?)
    }
}

impl<'de> BorrowDecode<'de> for &'de str {
    unsafe fn borrow_decode_unchecked<D: Decoder>(decoder: &mut D, buf: &'de [u8]) -> Self {
        let len = unsafe { decoder.get_u32_unchecked(buf) };
        unsafe { decoder.get_str_unchecked(buf, len as usize) }
    }

    fn borrow_decode<D: Decoder>(decoder: &mut D, buf: &'de [u8]) -> Result<Self, D::Error> {
        let len = decoder.get_u32(buf)?;
        Ok(decoder.get_str(buf, len as usize)?)
    }
}
